package logic

import (
	"context"
	"errors"
	"goods_srv/cache"
	"goods_srv/goods"
	"goods_srv/internal/svc"
	"goods_srv/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateGoodsLogic {
	return &CreateGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateGoodsLogic) CreateGoods(in *goods.CreateGoodsRequest) (*goods.CreateGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	var g models.Goods

	g.GoodsTitle = in.GoodsTitle
	g.GoodsDesc = in.GoodsDesc
	g.GoodsCover = in.GoodsCover
	g.GoodsPrice = float64(in.GoodsPrice)
	g.CheckStatus = int(in.CheckStatus)
	g.Status = int(in.Status)
	g.GoodsStock = int(in.GoodsStock)

	err = g.Create()
	if err != nil {
		logx.Error("发布商品失败")
		return nil, errors.New("发布商品失败")
	}

	//发布商品成功后，将商品库存放入Redis中
	cache.SynGoodsStock(int(g.ID), g.GoodsStock)

	return &goods.CreateGoodsResponse{
		GoodsId: int64(g.ID),
	}, nil
}
